#include "moparse.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <regex>
#include <algorithm>
#include <functional>
#include <set>
#include <cstdlib>  // 添加cstdlib头文件用于getenv
#include <iomanip>  // 添加iomanip头文件用于setw等格式化函数
#include <google/protobuf/stubs/common.h>

VerilogParser::VerilogParser() {
    // 初始化Protocol Buffers
    GOOGLE_PROTOBUF_VERIFY_VERSION;
}

VerilogParser::~VerilogParser() {
    // 清理Protocol Buffers
    google::protobuf::ShutdownProtobufLibrary();
}

bool VerilogParser::parseVerilogFile(const std::string& verilogFile, const std::string& moduleName) {
    try {
        std::cout << "开始解析文件: " << verilogFile << std::endl;
        
        std::string content = readFile(verilogFile);
        if (content.empty()) {
            std::cerr << "Error: Cannot read file " << verilogFile << std::endl;
            return false;
        }
        
        std::cout << "文件读取成功，大小: " << content.length() << " 字节" << std::endl;
        
        // 移除注释
        content = removeComments(content);
        std::cout << "注释移除完成" << std::endl;
        
        // 首先解析宏定义（无论是否有模块都要解析）
        parseMacros(content);
        std::cout << "宏定义解析完成" << std::endl;
        
        // 查找模块定义
        std::regex moduleRegex(R"(module\s+(\w+)\s*(?:\#?\s*\([^)]*\))?\s*\([^)]*\);)");
        std::smatch matches;
        
        std::string::const_iterator searchStart(content.cbegin());
        int moduleCount = 0;
        
        while (std::regex_search(searchStart, content.cend(), matches, moduleRegex)) {
            moduleCount++;
            std::string foundModuleName = matches[1].str();
            std::cout << "找到模块 #" << moduleCount << ": " << foundModuleName << std::endl;
            
            // 如果指定了模块名，只解析指定的模块
            if (!moduleName.empty() && foundModuleName != moduleName) {
                searchStart = matches.suffix().first;
                std::cout << "  跳过模块 (指定模块名: " << moduleName << ")" << std::endl;
                continue;
            }
            
            // 找到模块的完整内容
            size_t moduleStart = matches.prefix().length() + searchStart - content.cbegin();
            size_t moduleEnd = content.find("endmodule", moduleStart);
            
            if (moduleEnd == std::string::npos) {
                std::cerr << "Error: Module " << foundModuleName << " missing endmodule" << std::endl;
                searchStart = matches.suffix().first;
                continue;
            }
            
            moduleEnd += 9; // "endmodule" 长度
            std::string moduleContent = content.substr(moduleStart, moduleEnd - moduleStart);
            
            std::cout << "  模块内容大小: " << moduleContent.length() << " 字节" << std::endl;
            
            // 解析模块（但不再在parseModule中重复解析宏定义）
            std::cout << "  开始解析模块: " << foundModuleName << std::endl;
            auto module = parseModuleOnly(moduleContent, foundModuleName);
            if (module) {
                std::cout << "  模块解析成功" << std::endl;
                // 检查是否已存在同名模块
                int existingIndex = findModuleIndex(foundModuleName);
                if (existingIndex >= 0) {
                    // 替换现有模块
                    *database_.mutable_modules(existingIndex) = *module;
                    std::cout << "  替换现有模块" << std::endl;
                } else {
                    // 添加新模块
                    *database_.add_modules() = *module;
                    std::cout << "  添加新模块" << std::endl;
                }
            } else {
                std::cerr << "  模块解析失败: " << foundModuleName << std::endl;
            }
            
            searchStart = matches.suffix().first;
        }
        
        std::cout << "文件解析完成，共找到 " << moduleCount << " 个模块" << std::endl;
        return true;
    } catch (const std::exception& e) {
        std::cerr << "Error parsing file " << verilogFile << ": " << e.what() << std::endl;
        return false;
    }
}

bool VerilogParser::parseVerilogFileList(const std::string& fileList, const std::string& moduleName) {
    std::set<std::string> processedFiles;
    return parseVerilogFileListRecursive(fileList, moduleName, processedFiles);
}

bool VerilogParser::parseVerilogFileListRecursive(const std::string& fileList, const std::string& moduleName, std::set<std::string>& processedFiles) {
    try {
        std::cout << "解析文件列表: " << fileList << std::endl;
        
        // 解析环境变量
        std::string resolvedFileList = resolveEnvironmentVariables(fileList);
        std::cout << "解析后的文件列表路径: " << resolvedFileList << std::endl;
        
        // 防止循环引用
        std::string canonicalPath = resolvedFileList; // 简化处理，实际应该使用realpath
        if (processedFiles.find(canonicalPath) != processedFiles.end()) {
            std::cerr << "Warning: Circular reference detected, skipping file " << resolvedFileList << std::endl;
            return true;
        }
        processedFiles.insert(canonicalPath);
        
        std::ifstream file(resolvedFileList);
        if (!file.is_open()) {
            std::cerr << "Error: Cannot open file list " << resolvedFileList << std::endl;
            return false;
        }
        
        std::string line;
        bool success = true;
        int lineNumber = 0;
        
        while (std::getline(file, line)) {
            lineNumber++;
            std::cout << "处理第 " << lineNumber << " 行: " << line << std::endl;
            
            // 移除行首尾空格
            line.erase(0, line.find_first_not_of(" \t"));
            line.erase(line.find_last_not_of(" \t\r\n") + 1);
            
            // 跳过空行
            if (line.empty()) {
                std::cout << "  跳过空行" << std::endl;
                continue;
            }
            
            // 跳过各种类型的注释行
            if (isCommentOrDirective(line)) {
                std::cout << "  跳过注释行" << std::endl;
                continue;
            }
            
            // 处理VCS编译器指令
            if (isVCSDirective(line)) {
                std::cout << "  处理VCS指令: " << line << std::endl;
                if (!processVCSDirective(line, moduleName, processedFiles)) {
                    std::cerr << "Warning: Failed to process VCS directive " << line << std::endl;
                }
                continue;
            }
            
            // 解析环境变量
            std::string resolvedLine = resolveEnvironmentVariables(line);
            std::cout << "  解析环境变量后: " << resolvedLine << std::endl;
            
            // 检查是否是 -f 指令（嵌套文件列表）
            if (resolvedLine.length() > 3 && resolvedLine.substr(0, 3) == "-f ") {
                std::string nestedFileList = resolvedLine.substr(3);
                // 移除可能的引号
                if (nestedFileList.front() == '"' && nestedFileList.back() == '"') {
                    nestedFileList = nestedFileList.substr(1, nestedFileList.length() - 2);
                }
                
                std::cout << "Processing nested file list: " << nestedFileList << std::endl;
                
                // 递归解析嵌套的文件列表
                if (!parseVerilogFileListRecursive(nestedFileList, moduleName, processedFiles)) {
                    std::cerr << "Warning: Failed to parse nested file list " << nestedFileList << std::endl;
                    success = false;
                }
            } else {
                // 普通Verilog文件
                std::cout << "Processing Verilog file: " << resolvedLine << std::endl;
                
                if (!parseVerilogFile(resolvedLine, moduleName)) {
                    std::cerr << "Warning: Failed to parse file " << resolvedLine << std::endl;
                    success = false;
                }
            }
        }
        
        std::cout << "文件列表解析完成" << std::endl;
        return success;
    } catch (const std::exception& e) {
        std::cerr << "Error parsing file list: " << e.what() << std::endl;
        return false;
    }
}

bool VerilogParser::saveToModb(const std::string& outputFile) {
    try {
        std::ofstream file(outputFile, std::ios::binary);
        if (!file.is_open()) {
            std::cerr << "Error: Cannot create output file " << outputFile << std::endl;
            return false;
        }
        
        if (!database_.SerializeToOstream(&file)) {
            std::cerr << "Error: Failed to serialize data" << std::endl;
            return false;
        }
        
        return true;
    } catch (const std::exception& e) {
        std::cerr << "Error saving file: " << e.what() << std::endl;
        return false;
    }
}

bool VerilogParser::loadFromModb(const std::string& modbFile) {
    try {
        std::ifstream file(modbFile, std::ios::binary);
        if (!file.is_open()) {
            std::cerr << "Error: Cannot open .modb file " << modbFile << std::endl;
            return false;
        }
        
        if (!database_.ParseFromIstream(&file)) {
            std::cerr << "Error: Failed to deserialize data" << std::endl;
            return false;
        }
        
        return true;
    } catch (const std::exception& e) {
        std::cerr << "Error loading file: " << e.what() << std::endl;
        return false;
    }
}

bool VerilogParser::mergeToExistingModb(const std::string& existingFile) {
    try {
        modb::ModbDatabase existingDb;
        
        // 加载现有文件
        std::ifstream file(existingFile, std::ios::binary);
        if (file.is_open()) {
            if (!existingDb.ParseFromIstream(&file)) {
                std::cerr << "Error: Cannot parse existing .modb file" << std::endl;
                return false;
            }
            file.close();
        }
        
        // 合并模块
        for (const auto& newModule : database_.modules()) {
            bool found = false;
            for (int i = 0; i < existingDb.modules_size(); ++i) {
                if (existingDb.modules(i).name() == newModule.name()) {
                    // 替换现有模块
                    *existingDb.mutable_modules(i) = newModule;
                    found = true;
                    break;
                }
            }
            if (!found) {
                // 添加新模块
                *existingDb.add_modules() = newModule;
            }
        }
        
        // 保存合并后的数据
        std::ofstream outFile(existingFile, std::ios::binary);
        if (!outFile.is_open()) {
            std::cerr << "Error: Cannot write to file " << existingFile << std::endl;
            return false;
        }
        
        return existingDb.SerializeToOstream(&outFile);
    } catch (const std::exception& e) {
        std::cerr << "Error merging files: " << e.what() << std::endl;
        return false;
    }
}

void VerilogParser::showModuleInfo(const std::string& modbFile, const std::string& moduleName, bool verbose) {
    modb::ModbDatabase db;
    
    std::ifstream file(modbFile, std::ios::binary);
    if (!file.is_open()) {
        std::cerr << "Error: Cannot open .modb file " << modbFile << std::endl;
        return;
    }
    
    if (!db.ParseFromIstream(&file)) {
        std::cerr << "Error: Cannot parse .modb file" << std::endl;
        return;
    }
    
    // 显示宏定义
    if (db.macros_size() > 0) {
        std::cout << "Macro definitions (" << db.macros_size() << ")::" << std::endl;
        for (const auto& macro : db.macros()) {
            std::cout << "  `define " << macro.name();
            if (!macro.value().empty()) {
                std::cout << " " << macro.value();
            }
            std::cout << " [Type " << macro.type() << "]" << std::endl;
        }
        std::cout << std::endl;
    }
    
    for (const auto& module : db.modules()) {
        if (!moduleName.empty() && module.name() != moduleName) {
            continue;
        }
        
        std::cout << "Module name: " << module.name() << std::endl;
        
        if (verbose) {
            // 显示详细信息
            std::cout << "  Parameters (" << module.parameters_size() << "):" << std::endl;
            for (const auto& param : module.parameters()) {
                std::cout << "    " << param.name() << " = " << param.value() << std::endl;
            }
            
            std::cout << "  Ports (" << module.ports_size() << "):" << std::endl;
            for (const auto& port : module.ports()) {
                std::cout << "    " << port.direction() << " " << port.name();
                if (!port.width().empty()) {
                    std::cout << " [" << port.width() << "]";
                }
                std::cout << std::endl;
            }
            
            std::cout << "  Wires (" << module.wires_size() << "):" << std::endl;
            for (const auto& wire : module.wires()) {
                std::cout << "    " << wire.name();
                if (!wire.width().empty()) {
                    std::cout << " [" << wire.width() << "]";
                }
                std::cout << std::endl;
            }
            
            std::cout << "  Instances (" << module.instances_size() << "):" << std::endl;
            for (const auto& inst : module.instances()) {
                std::cout << "    " << inst.module_name() << " " << inst.name() << std::endl;
            }
        } else {
            // 显示简要信息
            int inputPorts = 0, outputPorts = 0, inoutPorts = 0;
            for (const auto& port : module.ports()) {
                if (port.direction() == "input") inputPorts++;
                else if (port.direction() == "output") outputPorts++;
                else if (port.direction() == "inout") inoutPorts++;
            }
            
            std::cout << "  Parameters: " << module.parameters_size()
                      << ", Input ports: " << inputPorts 
                      << ", Output ports: " << outputPorts
                      << ", Bidirectional ports: " << inoutPorts
                      << ", Instance count: " << module.instances_size() << std::endl;
        }
        std::cout << std::endl;
    }
}

bool VerilogParser::deleteModule(const std::string& modbFile, const std::string& moduleName) {
    try {
        modb::ModbDatabase db;
        
        std::ifstream file(modbFile, std::ios::binary);
        if (!file.is_open()) {
            std::cerr << "Error: Cannot open .modb file " << modbFile << std::endl;
            return false;
        }
        
        if (!db.ParseFromIstream(&file)) {
            std::cerr << "Error: Cannot parse .modb file" << std::endl;
            return false;
        }
        file.close();
        
        // 查找并删除模块
        bool found = false;
        for (int i = 0; i < db.modules_size(); ++i) {
            if (db.modules(i).name() == moduleName) {
                // 删除模块（通过重新构建数据库）
                modb::ModbDatabase newDb;
                for (int j = 0; j < db.modules_size(); ++j) {
                    if (j != i) {
                        *newDb.add_modules() = db.modules(j);
                    }
                }
                db = newDb;
                found = true;
                break;
            }
        }
        
        if (!found) {
            std::cerr << "Error: Module not found " << moduleName << std::endl;
            return false;
        }
        
        // 保存修改后的数据
        std::ofstream outFile(modbFile, std::ios::binary);
        if (!outFile.is_open()) {
            std::cerr << "Error: Cannot write to file " << modbFile << std::endl;
            return false;
        }
        
        return db.SerializeToOstream(&outFile);
    } catch (const std::exception& e) {
        std::cerr << "Error deleting module: " << e.what() << std::endl;
        return false;
    }
}

std::unique_ptr<modb::Module> VerilogParser::parseModule(const std::string& content, const std::string& moduleName) {
    auto module = std::make_unique<modb::Module>();
    module->set_name(moduleName);
    
    // 保存原始模块代码
    module->set_info(content);
    
    // 解析宏定义（在解析模块内容之前）
    parseMacros(content);
    
    // 解析各个部分
    parseParameters(content, module.get());
    parsePorts(content, module.get());
    parseWires(content, module.get());
    parseInstances(content, module.get());
    
    return module;
}

std::unique_ptr<modb::Module> VerilogParser::parseModuleOnly(const std::string& content, const std::string& moduleName) {
    auto module = std::make_unique<modb::Module>();
    if (!module) {
        return nullptr;
    }
    
    module->set_name(moduleName);
    
    // 保存原始模块代码
    module->set_info(content);
    
    try {
        // 不解析宏定义，只解析模块内容
        parseParameters(content, module.get());
        parsePorts(content, module.get());
        parseWires(content, module.get());
        parseInstances(content, module.get());
        
        // 为顶层端口添加连接信息
        addTopPortConnections(module.get());
    } catch (const std::exception& e) {
        std::cerr << "Error parsing module " << moduleName << ": " << e.what() << std::endl;
        return nullptr;
    }
    
    return module;
}

void VerilogParser::parseParameters(const std::string& content, modb::Module* module) {
    // 安全检查
    if (!module) {
        return;
    }
    
    try {
        // 解析parameter声明
        std::regex paramRegex(R"(parameter\s+(?:\[\s*\d+\s*:\s*\d+\s*\])?\s*(\w+)\s*=\s*([^;,]+))");
        std::smatch matches;
        
        std::string::const_iterator searchStart(content.cbegin());
        uint32_t paramId = 1;
        
        while (std::regex_search(searchStart, content.cend(), matches, paramRegex)) {
            auto param = module->add_parameters();
            if (!param) {  // 检查指针是否有效
                searchStart = matches.suffix().first;
                continue;
            }
            
            param->set_name(matches[1].str());
            
            std::string value = matches[2].str();
            // 移除前后空格
            value.erase(0, value.find_first_not_of(" \t"));
            value.erase(value.find_last_not_of(" \t") + 1);
            param->set_value(value);
            
            param->set_id(paramId++);
            
            searchStart = matches.suffix().first;
        }
    } catch (const std::exception& e) {
        // 如果解析过程中出现异常，记录错误但继续执行
        std::cerr << "Warning: Parameter parsing failed: " << e.what() << std::endl;
    }
}

void VerilogParser::parsePorts(const std::string& content, modb::Module* module) {
    // 安全检查
    if (!module) {
        return;
    }
    
    try {
        // 改进的端口解析 - 支持参数化位宽和复杂格式
        // 匹配: input/output/inout [optional type] [optional width] port_name
        std::regex portRegex(R"((input|output|inout)\s+(?:(wire|reg)\s+)?(?:\[\s*([^\]]+)\s*\]\s+)?(\w+))");
        std::smatch matches;
        
        std::string::const_iterator searchStart(content.cbegin());
        uint32_t portId = 1;
        
        while (std::regex_search(searchStart, content.cend(), matches, portRegex)) {
            std::string direction = matches[1].str();
            std::string type = matches[2].str().empty() ? "wire" : matches[2].str();
            std::string width = matches[3].str();
            std::string name = matches[4].str();
            
            // 过滤掉明显不是端口名的匹配（如注释中的词汇）
            if (name == "port" || name == "of" || name == "between" || name == "until" ||
                name == "the" || name == "to" || name == "and" || name == "or" ||
                name == "if" || name == "when" || name == "not" || name == "on" ||
                name == "for" || name == "at" || name == "in" || name == "with") {
                searchStart = matches.suffix().first;
                continue;
            }
            
            auto port = module->add_ports();
            if (!port) {  // 检查指针是否有效
                searchStart = matches.suffix().first;
                continue;
            }
            
            port->set_name(name);
            port->set_direction(direction);
            port->set_type(type);
            port->set_width(width);
            port->set_id(portId++);
            
            searchStart = matches.suffix().first;
        }
    } catch (const std::exception& e) {
        // 如果解析过程中出现异常，记录错误但继续执行
        std::cerr << "Warning: Port parsing failed: " << e.what() << std::endl;
    }
}

void VerilogParser::parseWires(const std::string& content, modb::Module* module) {
    // 安全检查
    if (!module) {
        return;
    }
    
    try {
        // 改进的wire解析 - 支持参数化位宽和复杂格式
        // 匹配: wire/reg [optional width] wire_name
        std::regex wireRegex(R"((wire|reg)\s+(?:\[\s*([^\]]+)\s*\]\s+)?(\w+))");
        std::smatch matches;
        
        std::string::const_iterator searchStart(content.cbegin());
        uint32_t wireId = 1;
        
        while (std::regex_search(searchStart, content.cend(), matches, wireRegex)) {
            std::string type = matches[1].str();
            std::string width = matches[2].str();
            std::string name = matches[3].str();
            
            // 过滤掉明显不是wire名的匹配（如注释中的词汇）
            if (name == "wire" || name == "of" || name == "between" || name == "until" ||
                name == "the" || name == "to" || name == "and" || name == "or" ||
                name == "if" || name == "when" || name == "not" || name == "on" ||
                name == "for" || name == "at" || name == "in" || name == "with") {
                searchStart = matches.suffix().first;
                continue;
            }
            
            auto wire = module->add_wires();
            if (!wire) {  // 检查指针是否有效
                searchStart = matches.suffix().first;
                continue;
            }
            
            wire->set_name(name);
            wire->set_width(width);
            wire->set_id(wireId++);
            
            searchStart = matches.suffix().first;
        }
    } catch (const std::exception& e) {
        // 如果解析过程中出现异常，记录错误但继续执行
        std::cerr << "Warning: Wire parsing failed: " << e.what() << std::endl;
    }
}

void VerilogParser::parseInstances(const std::string& content, modb::Module* module) {
    // 安全检查
    if (!module) {
        return;
    }
    
    try {
        // 增强的实例解析 - 解析端口连接信息
        // 匹配模块实例化: module_name #(...) instance_name (...port connections...);
        std::regex instRegex(R"((\w+)\s*(?:#\s*\([^)]*\))?\s+(\w+)\s*\(([^;]*?)\)\s*;)");
        std::smatch matches;
        
        std::string::const_iterator searchStart(content.cbegin());
        uint32_t instId = 1;
        
        while (std::regex_search(searchStart, content.cend(), matches, instRegex)) {
            std::string moduleTypeName = matches[1].str();
            std::string instanceName = matches[2].str();
            std::string portConnections = matches[3].str();
            
            // 过滤掉关键字
            if (moduleTypeName == "module" || moduleTypeName == "endmodule" ||
                moduleTypeName == "input" || moduleTypeName == "output" ||
                moduleTypeName == "inout" || moduleTypeName == "wire" ||
                moduleTypeName == "reg" || moduleTypeName == "assign") {
                searchStart = matches.suffix().first;
                continue;
            }
            
            auto inst = module->add_instances();
            if (!inst) {
                searchStart = matches.suffix().first;
                continue;
            }
            
            inst->set_module_name(moduleTypeName);
            inst->set_name(instanceName);
            inst->set_id(instId++);
            
            // 解析端口连接
            parsePortConnections(portConnections, instanceName, module);
            
            searchStart = matches.suffix().first;
        }
    } catch (const std::exception& e) {
        std::cerr << "Warning: Instance parsing failed: " << e.what() << std::endl;
    }
}

void VerilogParser::parsePortConnections(const std::string& connections, const std::string& instanceName, modb::Module* module) {
    if (!module || connections.empty()) {
        return;
    }
    
    try {
        // 解析端口连接: .port_name(signal_name)
        std::regex portConnRegex(R"(\.\s*(\w+)\s*\(\s*([^),]+)\s*\))");
        std::smatch matches;
        
        std::string::const_iterator searchStart(connections.cbegin());
        
        while (std::regex_search(searchStart, connections.cend(), matches, portConnRegex)) {
            std::string portName = matches[1].str();
            std::string signalName = matches[2].str();
            
            // 移除signal名称两端的空格
            signalName.erase(0, signalName.find_first_not_of(" \t"));
            signalName.erase(signalName.find_last_not_of(" \t") + 1);
            
            // 跳过空连接
            if (signalName.empty()) {
                searchStart = matches.suffix().first;
                continue;
            }
            
            // 查找或创建对应的wire
            modb::Wire* wire = nullptr;
            for (int i = 0; i < module->wires_size(); ++i) {
                if (module->mutable_wires(i)->name() == signalName) {
                    wire = module->mutable_wires(i);
                    break;
                }
            }
            
            // 如果没有找到wire，创建一个（可能是顶层端口或未声明的wire）
            if (!wire) {
                wire = module->add_wires();
                wire->set_name(signalName);
                wire->set_id(module->wires_size());
            }
            
            // 添加连接信息: instance_name.port_name
            auto conn = wire->add_connections();
            conn->set_name(instanceName + "." + portName);
            conn->set_type("INSTANCE_PORT");
            
            searchStart = matches.suffix().first;
        }
    } catch (const std::exception& e) {
        std::cerr << "Warning: Port connection parsing failed: " << e.what() << std::endl;
    }
}

void VerilogParser::addTopPortConnections(modb::Module* module) {
    if (!module) {
        return;
    }
    
    try {
        // 为每个顶层端口添加连接信息
        for (const auto& port : module->ports()) {
            std::string portName = port.name();
            
            // 查找以该端口名命名的wire
            modb::Wire* wire = nullptr;
            for (int i = 0; i < module->wires_size(); ++i) {
                if (module->mutable_wires(i)->name() == portName) {
                    wire = module->mutable_wires(i);
                    break;
                }
            }
            
            // 如果没有找到，创建一个
            if (!wire) {
                wire = module->add_wires();
                wire->set_name(portName);
                wire->set_width(port.width());
                wire->set_id(module->wires_size());
            }
            
            // 添加顶层端口连接
            auto conn = wire->add_connections();
            conn->set_name(portName);  // 顶层端口名
            conn->set_type("TOP_PORT");
        }
    } catch (const std::exception& e) {
        std::cerr << "Warning: Top port connection processing failed: " << e.what() << std::endl;
    }
}

void VerilogParser::parseMacros(const std::string& content) {
    try {
        // 解析宏定义
        std::regex macroRegex(R"(`define\s+(\w+)\s*(.*))");
        std::smatch matches;
        
        std::string::const_iterator searchStart(content.cbegin());
        
        while (std::regex_search(searchStart, content.cend(), matches, macroRegex)) {
            auto macro = database_.add_macros();
            if (!macro) {  // 检查指针是否有效
                searchStart = matches.suffix().first;
                continue;
            }
            
            macro->set_name(matches[1].str());
            macro->set_value(matches[2].str());
            
            // 判断宏类型
            std::string value = matches[2].str();
            if (value.empty()) {
                macro->set_type(0); // 纯定义宏开关
            } else if (value.find('(') != std::string::npos) {
                macro->set_type(2); // 有值表达式宏
            } else {
                macro->set_type(1); // 有值纯净宏
            }
            
            searchStart = matches.suffix().first;
        }
    } catch (const std::exception& e) {
        // 如果解析过程中出现异常，记录错误但继续执行
        std::cerr << "Warning: Macro parsing failed: " << e.what() << std::endl;
    }
}
std::string VerilogParser::readFile(const std::string& filename) {
    std::cout << "Reading file: " << filename << std::endl;
    
    // 解析环境变量
    std::string resolvedFilename = resolveEnvironmentVariables(filename);
    std::cout << "Resolved filename: " << resolvedFilename << std::endl;
    
    std::ifstream file(resolvedFilename);
    if (!file.is_open()) {
        std::cerr << "Error: Cannot open file " << resolvedFilename << std::endl;
        return "";
    }
    
    std::cout << "File opened successfully" << std::endl;
    
    std::stringstream buffer;
    buffer << file.rdbuf();
    
    std::cout << "File read completed, size: " << buffer.str().length() << " bytes" << std::endl;
    
    return buffer.str();
}

std::string VerilogParser::removeComments(const std::string& content) {
    std::string result = content;
    
    // 移除单行注释
    std::regex singleLineComment(R"(//.*$)");
    result = std::regex_replace(result, singleLineComment, "");
    
    // 移除多行注释
    std::regex multiLineComment(R"(/\*.*?\*/)");
    result = std::regex_replace(result, multiLineComment, "");
    
    return result;
}

bool VerilogParser::generateVerilog(const std::string& modbFile, const std::string& moduleName, 
                                    const std::string& outputFile, const std::string& mode) {
    try {
        modb::ModbDatabase db;
        
        std::ifstream file(modbFile, std::ios::binary);
        if (!file.is_open()) {
            std::cerr << "Error: Cannot open .modb file " << modbFile << std::endl;
            return false;
        }
        
        if (!db.ParseFromIstream(&file)) {
            std::cerr << "Error: Cannot parse .modb file" << std::endl;
            return false;
        }
        file.close();
        
        // 查找指定模块
        const modb::Module* targetModule = nullptr;
        for (const auto& module : db.modules()) {
            if (module.name() == moduleName) {
                targetModule = &module;
                break;
            }
        }
        
        if (!targetModule) {
            std::cerr << "Error: Module not found " << moduleName << std::endl;
            return false;
        }
        
        std::string verilogCode;
        
        if (mode == "e") {
            // 空壳模块
            verilogCode = generateEmptyModule(*targetModule, false);
        } else if (mode == "es") {
            // 空壳模块 + stub
            verilogCode = generateEmptyModule(*targetModule, true);
        } else if (mode == "a") {
            // 完整模块代码
            if (!targetModule->info().empty()) {
                verilogCode = targetModule->info();
            } else {
                // 如果没有原始代码，则生成空壳
                verilogCode = generateEmptyModule(*targetModule, false);
                std::cerr << "Warning: No original module code, generating empty shell" << std::endl;
            }
        } else if (mode == "i") {
            // 模块实例代码
            verilogCode = generateInstance(*targetModule);
        } else {
            std::cerr << "错误: 不支持的模式 " << mode << std::endl;
            return false;
        }
        
        // 写入输出文件
        std::ofstream outFile(outputFile);
        if (!outFile.is_open()) {
            std::cerr << "Error: Cannot create output file " << outputFile << std::endl;
            return false;
        }
        
        outFile << verilogCode;
        outFile.close();
        
        return true;
    } catch (const std::exception& e) {
        std::cerr << "Error generating Verilog code: " << e.what() << std::endl;
        return false;
    }
}

// 命令行处理函数实现
namespace moparse {

void showHelp() {
    std::cout << "moparse - Verilog模块解析器\n\n";
    std::cout << "用法:\n";
    std::cout << "  解析Verilog文件:\n";
    std::cout << "    moparse -v input.v -o output.modb\n";
    std::cout << "    moparse -v input.v -o output.modb -m moduleName\n";
    std::cout << "  合并到现有文件:\n";
    std::cout << "    moparse -v input.v -e exist.modb\n";
    std::cout << "    moparse -v input.v -e exist.modb -m moduleName\n";
    std::cout << "  解析文件列表:\n";
    std::cout << "    moparse -f verilog.list -o output.modb\n";
    std::cout << "    moparse -f verilog.list -all -o output.modb\n";
    std::cout << "  显示模块信息:\n";
    std::cout << "    moparse -s input.modb\n";
    std::cout << "    moparse -s input.modb -m moduleName\n";
    std::cout << "    moparse -sv input.modb\n";
    std::cout << "    moparse -sv input.modb -m moduleName\n";
    std::cout << "  删除模块:\n";
    std::cout << "    moparse -i input.modb -dm moduleName\n";
    std::cout << "  Reverse Verilog generation:\n";
    std::cout << "    moparse -i input.modb -m moduleName -oe output.v    # 空壳模块\n";
    std::cout << "    moparse -i input.modb -m moduleName -oes output.v   # 空壳+stub\n";
    std::cout << "    moparse -i input.modb -m moduleName -oa output.v    # Complete code\n";
    std::cout << "    moparse -i input.modb -m moduleName -oi output.v    # Instance code\n";
    std::cout << "  模块比较:\n";
    std::cout << "    moparse -i input.modb -m moduleName -r reference.modb     # 比较相同模块名\n";
    std::cout << "    moparse -i input.modb -m moduleName -r reference.modb -rm refModuleName  # 比较不同模块名\n";
    std::cout << "  连接关系显示:\n";
    std::cout << "    moparse -i input.modb -m moduleName --show-connect-top2sub                # 显示顶层到子模块连接\n";
    std::cout << "    moparse -i input.modb -m moduleName --show-connect-top2sub -s subName     # 显示指定子模块连接\n";
    std::cout << "    moparse -i input.modb -m moduleName --show-connect-sub2sub -sa subA -sb subB  # 显示子模块间连接\n";
    std::cout << "    moparse -i input.modb -m moduleName --export-dot output.dot               # 导出为DOT格式\n";
    std::cout << "    moparse -i input.modb -m moduleName --export-dot output.dot -sf subName   # 导出指定子模块连接\n";
    std::cout << "  例化层次显示:\n";
    std::cout << "    moparse -i input.modb -m moduleName --show-hierarchy                      # 显示模块例化层次\n";
    std::cout << "\n选项:\n";
    std::cout << "  -v FILE     Specify Verilog file\n";
    std::cout << "  -f FILE     Specify Verilog file list\n";
    std::cout << "  -o FILE     Specify output .modb file\n";
    std::cout << "  -e FILE     Merge to existing .modb file\n";
    std::cout << "  -m MODULE   Specify module name\n";
    std::cout << "  -s FILE     Show .modb file info\n";
    std::cout << "  -sv FILE    Show detailed .modb file info\n";
    std::cout << "  -i FILE     Specify .modb file to modify\n";
    std::cout << "  -dm MODULE  Delete specified module\n";
    std::cout << "  -oe FILE    Reverse generate empty shell module\n";
    std::cout << "  -oes FILE   Reverse generate empty shell module+stub\n";
    std::cout << "  -oa FILE    Reverse generate complete module code\n";
    std::cout << "  -oi FILE    Reverse generate module instance code\n";
    std::cout << "  -r FILE     Reference .modb file for comparison\n";
    std::cout << "  -rm MODULE  Reference module name for comparison\n";
    std::cout << "  --show-connect-top2sub  Show connections from top module to submodules\n";
    std::cout << "  --show-connect-sub2sub  Show connections between submodules\n";
    std::cout << "  --show-hierarchy        Show module instantiation hierarchy\n";
    std::cout << "  --export-dot FILE       Export connections to DOT format (for Graphviz)\n";
    std::cout << "  -s MODULE   Specify submodule name for connection display (use with --show-connect-*)\n";
    std::cout << "  -sf MODULE  Specify submodule filter for DOT export (use with --export-dot)\n";
    std::cout << "  -sa MODULE  Specify first submodule for sub2sub connection display\n";
    std::cout << "  -sb MODULE  Specify second submodule for sub2sub connection display\n";
    std::cout << "  -all        Parse all modules\n";
    std::cout << "  -h, --help  Show help information\n";
    std::cout << "  --version   Show version information\n";
}

void showVersion() {
    std::cout << "moparse version 1.0.0\n";
    std::cout << "Verilog模块解析器 - CrystalFlowAnalyzer项目组件\n";
}

int main(int argc, char* argv[]) {
    if (argc < 2) {
        showHelp();
        return 1;
    }
    
    // 命令行选项
    std::string verilogFile;
    std::string fileList;
    std::string outputFile;
    std::string existingFile;
    std::string moduleName;
    std::string showFile;
    std::string inplaceFile;
    std::string deleteModule;
    std::string generateMode;
    std::string generateOutput;
    std::string referenceFile;     // 用于模块比较的参考文件
    std::string referenceModule;   // 用于模块比较的参考模块名
    std::string showConnectSubmodule;  // 用于显示顶层到子模块连接的指定子模块名
    std::string connectSubmoduleA;     // 用于显示子模块间连接的第一个子模块名
    std::string connectSubmoduleB;     // 用于显示子模块间连接的第二个子模块名
    std::string dotOutputFile;         // DOT格式输出文件
    std::string dotSubmoduleFilter;    // DOT导出时的子模块过滤器
    bool verbose = false;
    bool parseAll = false;
    bool showConnectTop2Sub = false;   // 显示顶层到子模块连接
    bool showConnectSub2Sub = false;   // 显示子模块间连接
    bool exportDot = false;            // 导出为DOT格式
    bool showHierarchy = false;        // 显示模块例化层次关系
    
    // 解析命令行参数
    for (int i = 1; i < argc; ++i) {
        std::string arg = argv[i];
        
        if (arg == "-h" || arg == "--help") {
            showHelp();
            return 0;
        } else if (arg == "--version") {
            showVersion();
            return 0;
        } else if (arg == "-v" && i + 1 < argc) {
            verilogFile = argv[++i];
        } else if (arg == "-f" && i + 1 < argc) {
            fileList = argv[++i];
        } else if (arg == "-o" && i + 1 < argc) {
            outputFile = argv[++i];
        } else if (arg == "-e" && i + 1 < argc) {
            existingFile = argv[++i];
        } else if (arg == "-m" && i + 1 < argc) {
            moduleName = argv[++i];
        } else if (arg == "-s" && i + 1 < argc) {
            // 注意：-s 参数可能用于显示.modb文件信息或指定子模块名
            // 我们需要根据上下文判断其用途
            if (!inplaceFile.empty() && (showConnectTop2Sub || showConnectSub2Sub)) {
                // 在连接关系显示模式下，-s 用于指定子模块名
                showConnectSubmodule = argv[++i];
            } else {
                // 否则，-s 用于显示.modb文件信息
                showFile = argv[++i];
            }
        } else if (arg == "-sv" && i + 1 < argc) {
            showFile = argv[++i];
            verbose = true;
        } else if (arg == "-i" && i + 1 < argc) {
            inplaceFile = argv[++i];
        } else if (arg == "-dm" && i + 1 < argc) {
            deleteModule = argv[++i];
        } else if (arg == "-oe" && i + 1 < argc) {
            generateMode = "e";
            generateOutput = argv[++i];
        } else if (arg == "-oes" && i + 1 < argc) {
            generateMode = "es";
            generateOutput = argv[++i];
        } else if (arg == "-oa" && i + 1 < argc) {
            generateMode = "a";
            generateOutput = argv[++i];
        } else if (arg == "-oi" && i + 1 < argc) {
            generateMode = "i";
            generateOutput = argv[++i];
        } else if (arg == "-r" && i + 1 < argc) {  // 解析-r参数
            referenceFile = argv[++i];
        } else if (arg == "-rm" && i + 1 < argc) {  // 解析-rm参数
            referenceModule = argv[++i];
        } else if (arg == "--show-connect-top2sub") {
            showConnectTop2Sub = true;
        } else if (arg == "--show-connect-sub2sub") {
            showConnectSub2Sub = true;
        } else if (arg == "--show-hierarchy") {
            showHierarchy = true;
        } else if (arg == "--export-dot" && i + 1 < argc) {
            exportDot = true;
            dotOutputFile = argv[++i];
        } else if (arg == "-sa" && i + 1 < argc) {
            connectSubmoduleA = argv[++i];
        } else if (arg == "-sb" && i + 1 < argc) {
            connectSubmoduleB = argv[++i];
        } else if (arg == "-sf" && i + 1 < argc) {
            dotSubmoduleFilter = argv[++i];
        } else if (arg == "-all") {
            parseAll = true;
        }
    }
    
    VerilogParser parser;
    
    // 处理显示操作
    if (!showFile.empty()) {
        parser.showModuleInfo(showFile, moduleName, verbose);
        return 0;
    }
    
    // 处理模块比较操作
    if (!inplaceFile.empty() && !moduleName.empty() && !referenceFile.empty()) {
        // 如果没有指定参考模块名，则使用相同的模块名
        std::string refModuleName = referenceModule.empty() ? moduleName : referenceModule;
        parser.compareModules(inplaceFile, moduleName, referenceFile, refModuleName);
        return 0;
    }
    
    // 处理连接关系显示操作
    if (!inplaceFile.empty() && !moduleName.empty() && showConnectTop2Sub) {
        parser.showConnectionsTop2Sub(inplaceFile, moduleName, showConnectSubmodule);
        return 0;
    }
    
    // 处理子模块间连接关系显示操作
    if (!inplaceFile.empty() && !moduleName.empty() && showConnectSub2Sub) {
        if (connectSubmoduleA.empty() || connectSubmoduleB.empty()) {
            std::cerr << "Error: --show-connect-sub2sub requires both -sa and -sb parameters" << std::endl;
            return 1;
        }
        parser.showConnectionsSub2Sub(inplaceFile, moduleName, connectSubmoduleA, connectSubmoduleB);
        return 0;
    }
    
    // 处理DOT导出操作
    if (!inplaceFile.empty() && !moduleName.empty() && exportDot) {
        if (dotOutputFile.empty()) {
            std::cerr << "Error: --export-dot requires an output file path" << std::endl;
            return 1;
        }
        if (parser.exportConnectionsToDot(inplaceFile, moduleName, dotOutputFile, dotSubmoduleFilter)) {
            return 0;
        } else {
            return 1;
        }
    }
    
    // 处理层次结构显示操作
    if (!inplaceFile.empty() && !moduleName.empty() && showHierarchy) {
        parser.showHierarchy(inplaceFile, moduleName);
        return 0;
    }
    
    // 处理反向生成操作
    if (!generateMode.empty() && !generateOutput.empty()) {
        if (inplaceFile.empty() || moduleName.empty()) {
            std::cerr << "Error: Reverse generation requires -i and -m parameters" << std::endl;
            return 1;
        }
        
        VerilogParser parser;
        if (parser.generateVerilog(inplaceFile, moduleName, generateOutput, generateMode)) {
            std::cout << "Successfully generated Verilog code to: " << generateOutput << std::endl;
            return 0;
        } else {
            return 1;
        }
    }
    
    // 处理删除操作
    if (!inplaceFile.empty() && !deleteModule.empty()) {
        if (parser.deleteModule(inplaceFile, deleteModule)) {
            std::cout << "成功删除模块: " << deleteModule << std::endl;
            return 0;
        } else {
            return 1;
        }
    }
    
    // 处理解析操作
    bool success = false;
    
    if (!verilogFile.empty()) {
        success = parser.parseVerilogFile(verilogFile, parseAll ? "" : moduleName);
    } else if (!fileList.empty()) {
        success = parser.parseVerilogFileList(fileList, parseAll ? "" : moduleName);
    } else {
        std::cerr << "错误: 需要指定输入文件(-v 或 -f)" << std::endl;
        return 1;
    }
    
    if (!success) {
        std::cerr << "解析失败" << std::endl;
        return 1;
    }
    
    // 保存结果
    if (!outputFile.empty()) {
        if (parser.saveToModb(outputFile)) {
            std::cout << "Successfully saved to: " << outputFile << std::endl;
        } else {
            return 1;
        }
    } else if (!existingFile.empty()) {
        if (parser.mergeToExistingModb(existingFile)) {
            std::cout << "成功合并到: " << existingFile << std::endl;
        } else {
            return 1;
        }
    } else {
        std::cerr << "错误: 需要指定输出文件(-o 或 -e)" << std::endl;
        return 1;
    }
    
    return 0;
}

} // namespace moparse

int VerilogParser::findModuleIndex(const std::string& moduleName) {
    for (int i = 0; i < database_.modules_size(); ++i) {
        if (database_.modules(i).name() == moduleName) {
            return i;
        }
    }
    return -1;
}

std::string VerilogParser::generateEmptyModule(const modb::Module& module, bool withStub) {
    std::stringstream ss;
    
    // 模块头
    ss << "module " << module.name();
    
    // 参数列表
    if (module.parameters_size() > 0) {
        ss << " #(\n";
        for (int i = 0; i < module.parameters_size(); ++i) {
            const auto& param = module.parameters(i);
            ss << "    parameter " << param.name() << " = " << param.value();
            if (i < module.parameters_size() - 1) {
                ss << ",";
            }
            ss << "\n";
        }
        ss << ")";
    }
    
    // 端口列表
    if (module.ports_size() > 0) {
        ss << " (\n";
        for (int i = 0; i < module.ports_size(); ++i) {
            const auto& port = module.ports(i);
            
            // 检查是否有属性（宏隔离）
            if (!port.attribute().empty()) {
                ss << "    " << port.attribute() << "\n";
            }
            
            ss << "    " << port.direction() << " ";
            if (!port.width().empty()) {
                ss << "[" << port.width() << "] ";
            }
            ss << port.name();
            
            if (i < module.ports_size() - 1) {
                ss << ",";
            }
            ss << "\n";
            
            if (!port.attribute().empty()) {
                ss << "    `endif\n";  // 假设属性是`ifdef类型
            }
        }
        ss << ")";
    }
    
    ss << ";\n\n";
    
    // 如果需要stub，为输出端口添加assign 0
    if (withStub) {
        for (const auto& port : module.ports()) {
            if (port.direction() == "output") {
                ss << "assign " << port.name() << " = ";
                if (!port.width().empty()) {
                    // 解析位宽，生成对应的零值
                    std::string width = port.width();
                    size_t colonPos = width.find(':');
                    if (colonPos != std::string::npos) {
                        std::string msbStr = width.substr(0, colonPos);
                        std::string lsbStr = width.substr(colonPos + 1);
                        try {
                            int msb = std::stoi(msbStr);
                            int lsb = std::stoi(lsbStr);
                            int bitWidth = msb - lsb + 1;
                            ss << bitWidth << "'b0";
                        } catch (...) {
                            ss << "0";  // 默认值
                        }
                    } else {
                        ss << "0";
                    }
                } else {
                    ss << "0";
                }
                ss << ";\n";
            }
        }
        ss << "\n";
    }
    
    ss << "endmodule\n";
    
    return ss.str();
}

std::string VerilogParser::generateInstance(const modb::Module& module, const std::string& instanceName) {
    std::stringstream ss;
    
    std::string instName = instanceName.empty() ? ("u_" + module.name()) : instanceName;
    
    // 模块名
    ss << module.name();
    
    // 参数
    if (module.parameters_size() > 0) {
        ss << " #(\n";
        for (int i = 0; i < module.parameters_size(); ++i) {
            const auto& param = module.parameters(i);
            ss << "    ." << param.name() << "(" << param.name() << ")";
            if (i < module.parameters_size() - 1) {
                ss << ",";
            }
            ss << "\n";
        }
        ss << ")";
    }
    
    // 实例名
    ss << " " << instName;
    
    // 端口连接
    if (module.ports_size() > 0) {
        ss << " (\n";
        for (int i = 0; i < module.ports_size(); ++i) {
            const auto& port = module.ports(i);
            ss << "    ." << port.name() << "(" << port.name() << ")";
            if (i < module.ports_size() - 1) {
                ss << ",";
            }
            ss << "\n";
        }
        ss << ")";
    }
    
    ss << ";\n";
    
    return ss.str();
}

bool VerilogParser::isCommentOrDirective(const std::string& line) {
    if (line.empty()) {
        return true;
    }
    
    // 检查各种注释类型
    if (line[0] == '#') {                           // # 注释
        return true;
    }
    
    // 检查 // 注释（但要区分文件路径）
    if (line.length() >= 2 && line.substr(0, 2) == "//") {
        return true;
    }
    
    // 检查 /* 注释
    if (line.length() >= 2 && line.substr(0, 2) == "/*") {
        return true;
    }
    
    // 检查Synopsys工具生成的行
    if (line.find("component:") != std::string::npos ||  // Synopsys工具生成的component行
        line.find("library:") != std::string::npos ||    // Synopsys工具生成的library行
        line.find("files:") != std::string::npos) {      // Synopsys工具生成的files行
        return true;
    }
    
    return false;
}

bool VerilogParser::isVCSDirective(const std::string& line) {
    // VCS编译器指令识别
    if (line.length() > 1 && line[0] == '+') {
        // +define+, +incdir+, +libext+, +v2k, +sv 等
        if (line.find("+define+") == 0 ||     // 宏定义
            line.find("+incdir+") == 0 ||     // 包含目录
            line.find("+libext+") == 0 ||     // 库扩展名
            line.find("+libdir+") == 0 ||     // 库目录
            line.find("+v2k") == 0 ||         // Verilog-2001
            line.find("+sv") == 0 ||          // SystemVerilog
            line.find("+systemverilog") == 0 || // SystemVerilog 完整形式
            line.find("+systemverilogext+") == 0 || // SystemVerilog扩展名
            line.find("+verilogext+") == 0 || // Verilog扩展名
            line.find("+acc") == 0 ||         // 访问控制
            line.find("+delay_mode") == 0 ||  // 延迟模式
            line.find("+transport_int_delays") == 0 || // 传输延迟
            line.find("+pulse_int_e") == 0 || // 脉冲控制
            line.find("+pulse_int_r") == 0 || // 脉冲控制
            line.find("+compsdf") == 0 ||     // SDF编译
            line.find("+maxdelays") == 0 ||   // 最大延迟
            line.find("+mindelays") == 0 ||   // 最小延迟
            line.find("+typdelays") == 0) {   // 典型延迟
            return true;
        }
    }
    
    // 其他VCS指令
    if (line.find("-timescale") == 0 ||    // 时间刻度
        line.find("-y ") == 0 ||            // 库目录
        line.find("-v ") == 0 ||            // 库文件
        line.find("-P") == 0 ||             // PLI应用
        line.find("-l ") == 0 ||            // 日志文件
        line.find("-cm ") == 0 ||           // 覆盖率
        line.find("-debug") == 0 ||         // 调试模式
        line.find("-assert") == 0 ||        // 断言
        line.find("-sverilog") == 0) {      // SystemVerilog
        return true;
    }
    
    return false;
}

bool VerilogParser::processVCSDirective(const std::string& line, const std::string& moduleName, std::set<std::string>& processedFiles) {
    // 处理 +define+ 指令
    if (line.find("+define+") == 0) {
        std::string defineContent = line.substr(8); // 去掉 "+define+"
        
        // 分析宏定义格式
        size_t equalPos = defineContent.find('=');
        std::string macroName, macroValue;
        
        if (equalPos != std::string::npos) {
            macroName = defineContent.substr(0, equalPos);
            macroValue = defineContent.substr(equalPos + 1);
        } else {
            macroName = defineContent;
            macroValue = ""; // 开关型宏定义
        }
        
        // 添加到数据库的宏定义中
        auto* macro = database_.add_macros();
        macro->set_name(macroName);
        macro->set_value(macroValue);
        
        // 判断宏类型
        if (macroValue.empty()) {
            macro->set_type(0); // 纯定义宏开关
        } else if (macroValue.find('(') != std::string::npos) {
            macro->set_type(2); // 有值表达式宏
        } else {
            macro->set_type(1); // 有值纯净宏
        }
        
        std::cout << "处理宏定义: " << macroName << " = " << macroValue << std::endl;
        return true;
    }
    
    // 处理 +incdir+ 指令
    if (line.find("+incdir+") == 0) {
        std::string includePath = line.substr(8); // 去掉 "+incdir+"
        std::cout << "处理包含目录: " << includePath << std::endl;
        // TODO: 可以记录包含目录，用于后续的`include文件查找
        return true;
    }
    
    // 处理 -f 文件列表（可能以 -f 开头的特殊格式）
    if (line.find("-f ") == 0) {
        std::string nestedFileList = line.substr(3);
        std::cout << "处理嵌套文件列表: " << nestedFileList << std::endl;
        return parseVerilogFileListRecursive(nestedFileList, moduleName, processedFiles);
    }
    
    // 对于其他VCS指令，暂时只记录但不处理
    std::cout << "跳过VCS指令: " << line << std::endl;
    return true;
}

// 显示模块层次结构的辅助函数
void VerilogParser::showHierarchy(const std::string& modbFile, const std::string& moduleName) {
    // 加载.modb文件
    modb::ModbDatabase db;
    std::ifstream file(modbFile, std::ios::binary);
    if (!file.is_open()) {
        std::cerr << "Error: Cannot open .modb file " << modbFile << std::endl;
        return;
    }
    
    if (!db.ParseFromIstream(&file)) {
        std::cerr << "Error: Cannot parse .modb file " << modbFile << std::endl;
        return;
    }
    file.close();
    
    // 查找模块
    const modb::Module* module = nullptr;
    for (const auto& m : db.modules()) {
        if (m.name() == moduleName) {
            module = &m;
            break;
        }
    }
    
    if (!module) {
        std::cerr << "Error: Module " << moduleName << " not found in " << modbFile << std::endl;
        return;
    }
    
    // 创建模块名到模块对象的映射，便于快速查找
    std::map<std::string, const modb::Module*> moduleMap;
    for (const auto& m : db.modules()) {
        moduleMap[m.name()] = &m;
    }
    
    // 递归显示层次结构的辅助函数
    std::function<void(const std::string&, const std::string&, std::set<std::string>&, bool)> 
    printHierarchyRecursive = [&](const std::string& modName, const std::string& prefix, 
                                   std::set<std::string>& visitedPath, bool isLast) {
        // 检查是否存在循环引用
        if (visitedPath.find(modName) != visitedPath.end()) {
            std::cout << prefix << (isLast ? "└── " : "├── ") 
                      << modName << " [循环引用]" << std::endl;
            return;
        }
        
        // 查找模块
        auto it = moduleMap.find(modName);
        if (it == moduleMap.end()) {
            std::cout << prefix << (isLast ? "└── " : "├── ") 
                      << modName << " [模块未找到]" << std::endl;
            return;
        }
        
        const modb::Module* mod = it->second;
        
        // 输出当前模块
        std::cout << prefix << (isLast ? "└── " : "├── ") << modName;
        
        // 如果有参数，显示参数信息
        if (mod->parameters_size() > 0) {
            std::cout << " #(";
            bool first = true;
            for (const auto& param : mod->parameters()) {
                if (!first) std::cout << ", ";
                std::cout << param.name();
                if (!param.value().empty()) {
                    std::cout << "=" << param.value();
                }
                first = false;
            }
            std::cout << ")";
        }
        std::cout << std::endl;
        
        // 如果没有实例，返回
        if (mod->instances_size() == 0) {
            return;
        }
        
        // 将当前模块加入访问路径
        visitedPath.insert(modName);
        
        // 递归显示所有实例
        std::string newPrefix = prefix + (isLast ? "    " : "│   ");
        int instanceCount = mod->instances_size();
        int currentIndex = 0;
        
        for (const auto& instance : mod->instances()) {
            currentIndex++;
            bool isLastInstance = (currentIndex == instanceCount);
            
            // 输出实例名
            std::cout << newPrefix << (isLastInstance ? "└── " : "├── ") 
                      << instance.name() << " (" << instance.module_name() << ")" << std::endl;
            
            // 递归显示子模块的层次结构
            std::string instancePrefix = newPrefix + (isLastInstance ? "    " : "│   ");
            std::set<std::string> newVisitedPath = visitedPath;
            printHierarchyRecursive(instance.module_name(), instancePrefix, newVisitedPath, true);
        }
        
        // 从访问路径中移除当前模块
        visitedPath.erase(modName);
    };
    
    // 开始显示层次结构
    std::cout << "\nModule Hierarchy:" << std::endl;
    std::cout << moduleName;
    
    // 显示顶层模块的参数
    if (module->parameters_size() > 0) {
        std::cout << " #(";
        bool first = true;
        for (const auto& param : module->parameters()) {
            if (!first) std::cout << ", ";
            std::cout << param.name();
            if (!param.value().empty()) {
                std::cout << "=" << param.value();
            }
            first = false;
        }
        std::cout << ")";
    }
    std::cout << std::endl;
    
    // 如果顶层模块没有实例，直接返回
    if (module->instances_size() == 0) {
        std::cout << "  (No instances)" << std::endl;
        return;
    }
    
    // 递归显示所有实例
    int instanceCount = module->instances_size();
    int currentIndex = 0;
    std::set<std::string> visitedPath;
    visitedPath.insert(moduleName);
    
    for (const auto& instance : module->instances()) {
        currentIndex++;
        bool isLastInstance = (currentIndex == instanceCount);
        
        // 输出实例名
        std::cout << (isLastInstance ? "└── " : "├── ") 
                  << instance.name() << " (" << instance.module_name() << ")" << std::endl;
        
        // 递归显示子模块的层次结构
        std::string instancePrefix = isLastInstance ? "    " : "│   ";
        std::set<std::string> newVisitedPath = visitedPath;
        printHierarchyRecursive(instance.module_name(), instancePrefix, newVisitedPath, true);
    }
}

// 添加环境变量解析函数的实现
std::string VerilogParser::resolveEnvironmentVariables(const std::string& path) {
    if (path.empty()) {
        return path;
    }
    
    std::string result = path;
    
    // 查找并替换环境变量，格式为 $VAR_NAME 或 ${VAR_NAME}
    std::regex envVarRegex(R"(\$(\w+|\{[^}]+\}))");
    std::smatch matches;
    
    try {
        while (std::regex_search(result, matches, envVarRegex)) {
            std::string varExpression = matches[0].str();  // 完整的变量表达式，如 $PROJ_ROOT 或 ${PROJ_ROOT}
            std::string varName = matches[1].str();        // 变量名，如 PROJ_ROOT
            
            // 处理 ${VAR_NAME} 格式，移除花括号
            if (!varName.empty() && varName.front() == '{' && varName.back() == '}') {
                varName = varName.substr(1, varName.length() - 2);
            }
            
            // 获取环境变量值
            const char* envValue = std::getenv(varName.c_str());
            std::string replacement = (envValue != nullptr) ? envValue : varExpression;  // 如果环境变量不存在，保持原样
            
            // 替换第一个匹配项
            result = matches.prefix().str() + replacement + matches.suffix().str();
        }
    } catch (const std::exception& e) {
        // 如果正则表达式处理出错，返回原始路径
        std::cerr << "Warning: Environment variable resolution failed for path: " << path << std::endl;
        return path;
    }
    
    return result;
}

void VerilogParser::compareModules(const std::string& modbFile1, const std::string& moduleName1, 
                                  const std::string& modbFile2, const std::string& moduleName2) {
    // 加载第一个.modb文件
    modb::ModbDatabase db1;
    std::ifstream file1(modbFile1, std::ios::binary);
    if (!file1.is_open()) {
        std::cerr << "Error: Cannot open .modb file " << modbFile1 << std::endl;
        return;
    }
    
    if (!db1.ParseFromIstream(&file1)) {
        std::cerr << "Error: Cannot parse .modb file " << modbFile1 << std::endl;
        return;
    }
    file1.close();
    
    // 加载第二个.modb文件
    modb::ModbDatabase db2;
    std::ifstream file2(modbFile2, std::ios::binary);
    if (!file2.is_open()) {
        std::cerr << "Error: Cannot open .modb file " << modbFile2 << std::endl;
        return;
    }
    
    if (!db2.ParseFromIstream(&file2)) {
        std::cerr << "Error: Cannot parse .modb file " << modbFile2 << std::endl;
        return;
    }
    file2.close();
    
    // 查找第一个模块
    const modb::Module* module1 = nullptr;
    for (const auto& module : db1.modules()) {
        if (module.name() == moduleName1) {
            module1 = &module;
            break;
        }
    }
    
    if (!module1) {
        std::cerr << "Error: Module " << moduleName1 << " not found in " << modbFile1 << std::endl;
        return;
    }
    
    // 查找第二个模块
    const modb::Module* module2 = nullptr;
    for (const auto& module : db2.modules()) {
        if (module.name() == moduleName2) {
            module2 = &module;
            break;
        }
    }
    
    if (!module2) {
        std::cerr << "Error: Module " << moduleName2 << " not found in " << modbFile2 << std::endl;
        return;
    }
    
    std::cout << "Comparing modules:" << std::endl;
    std::cout << "  Module 1: " << moduleName1 << " from " << modbFile1 << std::endl;
    std::cout << "  Module 2: " << moduleName2 << " from " << modbFile2 << std::endl;
    std::cout << std::endl;
    
    // 比较参数
    std::cout << "Parameters comparison:" << std::endl;
    std::map<std::string, std::string> params1, params2;
    
    // 收集第一个模块的参数
    for (const auto& param : module1->parameters()) {
        params1[param.name()] = param.value();
    }
    
    // 收集第二个模块的参数
    for (const auto& param : module2->parameters()) {
        params2[param.name()] = param.value();
    }
    
    // 比较参数
    bool hasParamDiff = false;
    for (const auto& pair : params1) {
        const std::string& paramName = pair.first;
        const std::string& paramValue1 = pair.second;
        
        auto it = params2.find(paramName);
        if (it == params2.end()) {
            std::cout << "  Only in " << moduleName1 << ": " << paramName << " = " << paramValue1 << std::endl;
            hasParamDiff = true;
        } else {
            const std::string& paramValue2 = it->second;
            if (paramValue1 != paramValue2) {
                std::cout << "  Different values for " << paramName << ":" << std::endl;
                std::cout << "    " << moduleName1 << ": " << paramValue1 << std::endl;
                std::cout << "    " << moduleName2 << ": " << paramValue2 << std::endl;
                hasParamDiff = true;
            }
        }
    }
    
    // 检查只在第二个模块中存在的参数
    for (const auto& pair : params2) {
        const std::string& paramName = pair.first;
        if (params1.find(paramName) == params1.end()) {
            std::cout << "  Only in " << moduleName2 << ": " << paramName << " = " << pair.second << std::endl;
            hasParamDiff = true;
        }
    }
    
    if (!hasParamDiff) {
        std::cout << "  All parameters are identical" << std::endl;
    }
    
    std::cout << std::endl;
    
    // 比较端口
    std::cout << "Ports comparison:" << std::endl;
    std::map<std::string, std::tuple<std::string, std::string, std::string>> ports1, ports2; // name -> (direction, width, type)
    
    // 收集第一个模块的端口
    for (const auto& port : module1->ports()) {
        ports1[port.name()] = std::make_tuple(port.direction(), port.width(), port.type());
    }
    
    // 收集第二个模块的端口
    for (const auto& port : module2->ports()) {
        ports2[port.name()] = std::make_tuple(port.direction(), port.width(), port.type());
    }
    
    // 比较端口
    bool hasPortDiff = false;
    for (const auto& pair : ports1) {
        const std::string& portName = pair.first;
        const auto& portInfo1 = pair.second;
        
        auto it = ports2.find(portName);
        if (it == ports2.end()) {
            std::cout << "  Only in " << moduleName1 << ": " << portName << " " 
                      << std::get<0>(portInfo1) << " " << std::get<2>(portInfo1);
            if (!std::get<1>(portInfo1).empty()) {
                std::cout << " [" << std::get<1>(portInfo1) << "]";
            }
            std::cout << std::endl;
            hasPortDiff = true;
        } else {
            const auto& portInfo2 = it->second;
            if (portInfo1 != portInfo2) {
                std::cout << "  Different definitions for " << portName << ":" << std::endl;
                std::cout << "    " << moduleName1 << ": " << std::get<0>(portInfo1) << " " 
                          << std::get<2>(portInfo1);
                if (!std::get<1>(portInfo1).empty()) {
                    std::cout << " [" << std::get<1>(portInfo1) << "]";
                }
                std::cout << std::endl;
                
                std::cout << "    " << moduleName2 << ": " << std::get<0>(portInfo2) << " " 
                          << std::get<2>(portInfo2);
                if (!std::get<1>(portInfo2).empty()) {
                    std::cout << " [" << std::get<1>(portInfo2) << "]";
                }
                std::cout << std::endl;
                hasPortDiff = true;
            }
        }
    }
    
    // 检查只在第二个模块中存在的端口
    for (const auto& pair : ports2) {
        const std::string& portName = pair.first;
        if (ports1.find(portName) == ports1.end()) {
            const auto& portInfo2 = pair.second;
            std::cout << "  Only in " << moduleName2 << ": " << portName << " " 
                      << std::get<0>(portInfo2) << " " << std::get<2>(portInfo2);
            if (!std::get<1>(portInfo2).empty()) {
                std::cout << " [" << std::get<1>(portInfo2) << "]";
            }
            std::cout << std::endl;
            hasPortDiff = true;
        }
    }
    
    if (!hasPortDiff) {
        std::cout << "  All ports are identical" << std::endl;
    }
    
    std::cout << std::endl;
    
    // 总结
    std::cout << "Summary:" << std::endl;
    std::cout << "  Parameters: " << (hasParamDiff ? "Different" : "Identical") << std::endl;
    std::cout << "  Ports: " << (hasPortDiff ? "Different" : "Identical") << std::endl;
}

void VerilogParser::showConnectionsTop2Sub(const std::string& modbFile, const std::string& moduleName, 
                                          const std::string& submodule) {
    // 加载.modb文件
    modb::ModbDatabase db;
    std::ifstream file(modbFile, std::ios::binary);
    if (!file.is_open()) {
        std::cerr << "Error: Cannot open .modb file " << modbFile << std::endl;
        return;
    }
    
    if (!db.ParseFromIstream(&file)) {
        std::cerr << "Error: Cannot parse .modb file " << modbFile << std::endl;
        return;
    }
    file.close();
    
    // 查找模块
    const modb::Module* module = nullptr;
    for (const auto& m : db.modules()) {
        if (m.name() == moduleName) {
            module = &m;
            break;
        }
    }
    
    if (!module) {
        std::cerr << "Error: Module " << moduleName << " not found in " << modbFile << std::endl;
        return;
    }
    
    std::cout << moduleName << ":" << std::endl;
    
    // 如果指定了子模块，检查该子模块是否存在
    if (!submodule.empty()) {
        bool submoduleExists = false;
        for (const auto& instance : module->instances()) {
            if (instance.name() == submodule) {
                submoduleExists = true;
                break;
            }
        }
        if (!submoduleExists) {
            std::cerr << "Warning: Submodule " << submodule << " not found in " << moduleName << std::endl;
            return;
        }
    }
    
    // 创建一个映射，用于存储每个端口连接到的实例端口
    // key: 顶层模块端口名, value: 连接到的实例端口列表 (实例名, 实例端口名)
    std::map<std::string, std::set<std::pair<std::string, std::string>>> portConnections;
    
    // 遍历所有线网，查找连接关系
    for (const auto& wire : module->wires()) {
        std::string wireName = wire.name();
        std::vector<std::string> topPorts;
        std::vector<std::pair<std::string, std::string>> instancePorts;  // (instance_name, port_name)
        
        // 分类收集连接到此线网的端口
        for (const auto& conn : wire.connections()) {
            std::string connName = conn.name();
            size_t dotPos = connName.find('.');
            
            if (dotPos == std::string::npos) {
                // 顶层端口
                topPorts.push_back(connName);
            } else {
                // 实例端口
                std::string instanceName = connName.substr(0, dotPos);
                std::string portName = connName.substr(dotPos + 1);
                instancePorts.push_back({instanceName, portName});
            }
        }
        
        // 建立顶层端口到实例端口的连接
        for (const auto& topPort : topPorts) {
            for (const auto& instPort : instancePorts) {
                // 如果指定了子模块，只处理指定子模块的连接
                if (submodule.empty() || instPort.first == submodule) {
                    portConnections[topPort].insert(instPort);
                }
            }
        }
    }
    
    // 显示端口到子模块的连接关系
    for (const auto& port : module->ports()) {
        std::string portName = port.name();
        std::string direction = port.direction();
        std::string width = port.width();
        
        auto it = portConnections.find(portName);
        if (it != portConnections.end()) {
            // 有连接的端口
            const auto& connections = it->second;
            bool firstConnection = true;
            
            for (const auto& conn : connections) {
                std::string instanceName = conn.first;
                std::string instancePort = conn.second;
                
                if (firstConnection) {
                    // 格式化输出端口信息
                    std::cout << "    ";
                    // 输出方向，左对齐，占8个字符
                    std::cout << std::left << std::setw(8) << direction;
                    
                    // 输出位宽（如果有的话）
                    if (!width.empty()) {
                        std::cout << "[" << width << "] ";
                    } else {
                        std::cout << "        "; // 8个空格用于对齐
                    }
                    
                    // 输出端口名
                    std::cout << std::left << std::setw(15) << portName;
                    
                    // 输出连接符号
                    std::cout << " ------  ";
                    
                    // 输出连接目标
                    std::cout << instanceName << "." << instancePort << std::endl;
                    
                    firstConnection = false;
                } else {
                    // 输出额外的连接（同一端口连接到多个实例）
                    std::cout << "                          |---- " << instanceName << "." << instancePort << std::endl;
                }
            }
        } else {
            // 没有连接的端口，显示tie off
            std::cout << "    ";
            std::cout << std::left << std::setw(8) << direction;
            
            if (!width.empty()) {
                std::cout << "[" << width << "] ";
            } else {
                std::cout << "        ";
            }
            
            std::cout << std::left << std::setw(15) << portName;
            std::cout << " ------  ";
            
            // 显示tie off
            if (direction == "input") {
                std::cout << "1'h0" << std::endl;
            } else {
                std::cout << "unconnected" << std::endl;
            }
        }
    }
}

void VerilogParser::showConnectionsSub2Sub(const std::string& modbFile, const std::string& moduleName, 
                                          const std::string& submoduleA, const std::string& submoduleB) {
    // 加载.modb文件
    modb::ModbDatabase db;
    std::ifstream file(modbFile, std::ios::binary);
    if (!file.is_open()) {
        std::cerr << "Error: Cannot open .modb file " << modbFile << std::endl;
        return;
    }
    
    if (!db.ParseFromIstream(&file)) {
        std::cerr << "Error: Cannot parse .modb file " << modbFile << std::endl;
        return;
    }
    file.close();
    
    // 查找顶层模块
    const modb::Module* module = nullptr;
    for (const auto& m : db.modules()) {
        if (m.name() == moduleName) {
            module = &m;
            break;
        }
    }
    
    if (!module) {
        std::cerr << "Error: Module " << moduleName << " not found in " << modbFile << std::endl;
        return;
    }
    
    // 检查子模块是否存在并获取模块名
    std::string moduleNameA, moduleNameB;
    bool submoduleAExists = false;
    bool submoduleBExists = false;
    
    for (const auto& instance : module->instances()) {
        if (instance.name() == submoduleA) {
            submoduleAExists = true;
            moduleNameA = instance.module_name();
        }
        if (instance.name() == submoduleB) {
            submoduleBExists = true;
            moduleNameB = instance.module_name();
        }
    }
    
    if (!submoduleAExists) {
        std::cerr << "Error: Submodule " << submoduleA << " not found in " << moduleName << std::endl;
        return;
    }
    
    if (!submoduleBExists) {
        std::cerr << "Error: Submodule " << submoduleB << " not found in " << moduleName << std::endl;
        return;
    }
    
    // 获取子模块A和B的模块定义
    const modb::Module* modA = nullptr;
    const modb::Module* modB = nullptr;
    
    for (const auto& m : db.modules()) {
        if (m.name() == moduleNameA) {
            modA = &m;
        }
        if (m.name() == moduleNameB) {
            modB = &m;
        }
    }
    
    if (!modA) {
        std::cerr << "Error: Module definition for " << moduleNameA << " not found" << std::endl;
        return;
    }
    
    if (!modB) {
        std::cerr << "Error: Module definition for " << moduleNameB << " not found" << std::endl;
        return;
    }
    
    // 创建端口信息映射
    // key: 端口名, value: (方向, 位宽)
    std::map<std::string, std::pair<std::string, std::string>> portInfoA, portInfoB;
    
    for (const auto& port : modA->ports()) {
        portInfoA[port.name()] = {port.direction(), port.width()};
    }
    
    for (const auto& port : modB->ports()) {
        portInfoB[port.name()] = {port.direction(), port.width()};
    }
    
    // 创建一个映射，用于存储子模块A和B之间的连接关系
    // key: 子模块A的端口, value: 子模块B的端口
    std::map<std::string, std::string> subConnections;
    
    // 遍历所有线网，查找子模块A和B之间的连接关系
    for (const auto& wire : module->wires()) {
        std::string wireName = wire.name();
        std::vector<std::pair<std::string, std::string>> connectedInstances; // (实例名, 端口名)
        
        // 收集连接到此线网的所有实例端口
        for (const auto& conn : wire.connections()) {
            std::string connName = conn.name();
            size_t dotPos = connName.find('.');
            if (dotPos != std::string::npos) {
                std::string instanceName = connName.substr(0, dotPos);
                std::string portName = connName.substr(dotPos + 1);
                connectedInstances.push_back({instanceName, portName});
            }
        }
        
        // 查找子模块A和B之间的连接
        std::string portA, portB;
        bool foundA = false, foundB = false;
        
        for (const auto& instPort : connectedInstances) {
            if (instPort.first == submoduleA) {
                portA = instPort.second;
                foundA = true;
            } else if (instPort.first == submoduleB) {
                portB = instPort.second;
                foundB = true;
            }
        }
        
        if (foundA && foundB) {
            subConnections[portA] = portB;
        }
    }
    
    // 显示标题
    std::cout << std::left << std::setw(30) << (submoduleA + ":") << " " << submoduleB << ":" << std::endl;
    
    // 显示连接关系
    for (const auto& conn : subConnections) {
        std::string portA = conn.first;
        std::string portB = conn.second;
        
        // 获取端口A的详细信息
        std::string directionA = "";
        std::string widthA = "";
        auto itA = portInfoA.find(portA);
        if (itA != portInfoA.end()) {
            directionA = itA->second.first;
            widthA = itA->second.second;
        }
        
        // 获取端口B的详细信息
        std::string directionB = "";
        std::string widthB = "";
        auto itB = portInfoB.find(portB);
        if (itB != portInfoB.end()) {
            directionB = itB->second.first;
            widthB = itB->second.second;
        }
        
        // 格式化输出端口A
        std::cout << "    ";
        std::cout << std::left << std::setw(8) << directionA;
        
        if (!widthA.empty()) {
            std::cout << "[" << widthA << "] ";
            // 计算填充空格数，使总宽度为8
            int padding = 8 - widthA.length() - 3; // 3是[]和空格
            if (padding > 0) {
                std::cout << std::string(padding, ' ');
            }
        } else {
            std::cout << "        "; // 8个空格
        }
        
        std::cout << std::left << std::setw(13) << portA;
        std::cout << "| ";
        
        // 格式化输出端口B
        std::cout << std::left << std::setw(8) << directionB;
        
        if (!widthB.empty()) {
            std::cout << " [" << widthB << "]   ";
            // 计算填充空格数
            int padding = 8 - widthB.length() - 3;
            if (padding > 0) {
                std::cout << std::string(padding, ' ');
            }
        } else {
            std::cout << "         "; // 9个空格
        }
        
        std::cout << portB << std::endl;
    }
    
    // 如果没有找到连接关系，提示用户
    if (subConnections.empty()) {
        std::cout << "No connections found between " << submoduleA << " and " << submoduleB << std::endl;
    }
}

bool VerilogParser::exportConnectionsToDot(const std::string& modbFile, const std::string& moduleName, 
                                          const std::string& outputFile, const std::string& submodule) {
    // 加载.modb文件
    modb::ModbDatabase db;
    std::ifstream file(modbFile, std::ios::binary);
    if (!file.is_open()) {
        std::cerr << "Error: Cannot open .modb file " << modbFile << std::endl;
        return false;
    }
    
    if (!db.ParseFromIstream(&file)) {
        std::cerr << "Error: Cannot parse .modb file " << modbFile << std::endl;
        return false;
    }
    file.close();
    
    // 查找模块
    const modb::Module* module = nullptr;
    for (const auto& m : db.modules()) {
        if (m.name() == moduleName) {
            module = &m;
            break;
        }
    }
    
    if (!module) {
        std::cerr << "Error: Module " << moduleName << " not found in " << modbFile << std::endl;
        return false;
    }
    
    // 打开输出文件
    std::ofstream outFile(outputFile);
    if (!outFile.is_open()) {
        std::cerr << "Error: Cannot create output file " << outputFile << std::endl;
        return false;
    }
    
    // 写入DOT文件头
    outFile << "digraph \"" << moduleName << "\" {" << std::endl;
    outFile << "    rankdir=LR;  // 从左到右布局" << std::endl;
    outFile << "    node [shape=box, style=\"rounded,filled\", fillcolor=lightblue];" << std::endl;
    outFile << "    edge [color=black];" << std::endl;
    outFile << std::endl;
    
    // 创建顶层模块节点
    outFile << "    // 顶层模块" << std::endl;
    outFile << "    \"" << moduleName << "\" [fillcolor=\"#90EE90\", label=\"" << moduleName << "\"];" << std::endl;
    outFile << std::endl;
    
    // 创建子模块节点
    outFile << "    // 子模块" << std::endl;
    for (const auto& instance : module->instances()) {
        if (submodule.empty() || instance.name() == submodule) {
            outFile << "    \"" << instance.name() << "\" [label=\"" << instance.name() 
                    << "\\n(" << instance.module_name() << ")\"];" << std::endl;
        }
    }
    outFile << std::endl;
    
    // 创建端口到子模块的连接
    outFile << "    // 连接关系" << std::endl;
    
    // 创建连接映射
    std::map<std::string, std::set<std::pair<std::string, std::string>>> portConnections;
    
    // 遍历所有线网，查找连接关系
    for (const auto& wire : module->wires()) {
        std::string wireName = wire.name();
        std::vector<std::string> topPorts;
        std::vector<std::pair<std::string, std::string>> instancePorts;
        
        // 分类收集连接到此线网的端口
        for (const auto& conn : wire.connections()) {
            std::string connName = conn.name();
            size_t dotPos = connName.find('.');
            
            if (dotPos == std::string::npos) {
                // 顶层端口
                topPorts.push_back(connName);
            } else {
                // 实例端口
                std::string instanceName = connName.substr(0, dotPos);
                std::string portName = connName.substr(dotPos + 1);
                instancePorts.push_back({instanceName, portName});
            }
        }
        
        // 建立顶层端口到实例端口的连接
        for (const auto& topPort : topPorts) {
            for (const auto& instPort : instancePorts) {
                // 如果指定了子模块，只处理指定子模块的连接
                if (submodule.empty() || instPort.first == submodule) {
                    portConnections[topPort].insert(instPort);
                }
            }
        }
    }
    
    // 输出连接
    for (const auto& port : module->ports()) {
        std::string portName = port.name();
        std::string direction = port.direction();
        std::string width = port.width();
        
        // 创建端口标签
        std::string portLabel = portName;
        if (!width.empty()) {
            portLabel += "[" + width + "]";
        }
        portLabel += "\\n(" + direction + ")";
        
        auto it = portConnections.find(portName);
        if (it != portConnections.end()) {
            // 有连接的端口
            const auto& connections = it->second;
            
            for (const auto& conn : connections) {
                std::string instanceName = conn.first;
                std::string instancePort = conn.second;
                
                // 根据方向设置边的样式
                std::string edgeStyle = "";
                if (direction == "input") {
                    // 输入端口：从顶层模块到子模块
                    outFile << "    \"" << moduleName << "\" -> \"" << instanceName 
                            << "\" [label=\"" << portLabel << "\\n->\\n" << instancePort << "\"]";
                } else if (direction == "output") {
                    // 输出端口：从子模块到顶层模块
                    outFile << "    \"" << instanceName << "\" -> \"" << moduleName 
                            << "\" [label=\"" << instancePort << "\\n->\\n" << portLabel << "\"]";
                } else {
                    // inout端口：双向箭头
                    outFile << "    \"" << moduleName << "\" -> \"" << instanceName 
                            << "\" [dir=both, label=\"" << portLabel << "\\n<->\\n" << instancePort << "\"]";
                }
                outFile << ";" << std::endl;
            }
        }
    }
    
    // 添加子模块间的连接
    outFile << std::endl << "    // 子模块间连接" << std::endl;
    
    // 记录已处理的连接，避免重复
    std::set<std::pair<std::string, std::string>> processedConnections;
    
    for (const auto& wire : module->wires()) {
        std::vector<std::pair<std::string, std::string>> instancePorts;
        
        // 收集连接到此线网的所有实例端口
        for (const auto& conn : wire.connections()) {
            std::string connName = conn.name();
            size_t dotPos = connName.find('.');
            if (dotPos != std::string::npos) {
                std::string instanceName = connName.substr(0, dotPos);
                std::string portName = connName.substr(dotPos + 1);
                
                // 如果指定了子模块，只处理相关连接
                if (submodule.empty() || instanceName == submodule) {
                    instancePorts.push_back({instanceName, portName});
                }
            }
        }
        
        // 创建子模块间的连接（排除自连接）
        for (size_t i = 0; i < instancePorts.size(); ++i) {
            for (size_t j = i + 1; j < instancePorts.size(); ++j) {
                std::string inst1 = instancePorts[i].first;
                std::string port1 = instancePorts[i].second;
                std::string inst2 = instancePorts[j].first;
                std::string port2 = instancePorts[j].second;
                
                // 避免自连接
                if (inst1 != inst2) {
                    // 创建唯一标识，避免重复
                    std::string connKey = inst1 < inst2 ? 
                        inst1 + "->" + inst2 + ":" + port1 + "-" + port2 :
                        inst2 + "->" + inst1 + ":" + port2 + "-" + port1;
                    
                    if (processedConnections.find({inst1, inst2}) == processedConnections.end() &&
                        processedConnections.find({inst2, inst1}) == processedConnections.end()) {
                        outFile << "    \"" << inst1 << "\" -> \"" << inst2 
                                << "\" [label=\"" << port1 << "\\n->\\n" << port2 
                                << "\", style=dashed, color=gray];" << std::endl;
                        processedConnections.insert({inst1, inst2});
                    }
                }
            }
        }
    }
    
    // 写入DOT文件尾
    outFile << "}" << std::endl;
    outFile.close();
    
    std::cout << "Successfully exported to DOT format: " << outputFile << std::endl;
    std::cout << "You can generate a graph using: dot -Tpng " << outputFile << " -o output.png" << std::endl;
    std::cout << "Or view it interactively: xdot " << outputFile << std::endl;
    
    return true;
}